/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dialogs.obra;

import dao.Dao;
import dao.DaoObra;
import dao.DaoUsuario;
import dialogs.JFramePrincipal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import libcontrol.model.Atividade;
import libcontrol.model.Exemplar;
import libcontrol.model.Obra;
import libcontrol.model.Reserva;
import libcontrol.model.Usuario;

/**
 *
 * @author marco
 */
public class JDialogVerObra extends javax.swing.JDialog {

    private Obra obra;

    /**
     * Creates new form JDialogVerObra
     */
    public JDialogVerObra(java.awt.Frame parent, boolean modal, Obra obra) {
        super(parent, modal);
        initComponents();
        DefaultComboBoxModel<Obra.Categoria> model = new DefaultComboBoxModel<>(Obra.Categoria.values());
        jComboBoxCategoria.setModel(model);
        this.obra = obra;
        preencherCampos();
        Usuario usuarioLogado = JFramePrincipal.getUsuarioLogado();

        boolean jaReservou = usuarioLogado.getReservaAtiva(obra) != null;
        if (usuarioLogado.getPerfil().getAtividades().contains(Atividade.RESERVAR_OBRAS)
                && !obra.getExemplaresAtivos().isEmpty()
                && !obra.hasExemplaresDisponiveis()) {
            if (!jaReservou && !usuarioLogado.hasEmprestimo(obra)) {
                jButtonReservarObra.setEnabled(true);
            } else {
                jButtonReservarObra.setText("Cancelar Reserva");
                jButtonReservarObra.setEnabled(true);
            }
        } else {
            jButtonReservarObra.setEnabled(false);
        }
        if (!usuarioLogado.getPerfil().getAtividades().contains(Atividade.GERENCIAR_ACERVO)) {
            jButtonAdicionarExemplares.setVisible(false);
            jButtonAlterarObra.setVisible(false);
            jButtonExcluirObra.setVisible(false);
            jButtonExcluirExemplares.setVisible(false);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jButtonExcluirExemplares = new javax.swing.JButton();
        jButtonAdicionarExemplares = new javax.swing.JButton();
        jLabelTitulo = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTableExemplares = new javax.swing.JTable();
        jTextFieldTitulo = new javax.swing.JTextField();
        jTextFieldQuantidadeDisponivel = new javax.swing.JTextField();
        jLabelQuantidadeDisponivel = new javax.swing.JLabel();
        jTextFieldQuantidade = new javax.swing.JTextField();
        jLabelAutor = new javax.swing.JLabel();
        jTextFieldEdicao = new javax.swing.JTextField();
        jTextFieldAutor = new javax.swing.JTextField();
        jComboBoxCategoria = new javax.swing.JComboBox();
        jLabelQuantidadeDisponivel1 = new javax.swing.JLabel();
        jLabelCategoria = new javax.swing.JLabel();
        jLabelEdicao = new javax.swing.JLabel();
        jTextFieldQuantidadeDisponivel1 = new javax.swing.JTextField();
        jLabelEditora = new javax.swing.JLabel();
        jLabelExemplaresDisponiveis = new javax.swing.JLabel();
        jLabelQuanditade = new javax.swing.JLabel();
        jTextFieldEditora = new javax.swing.JTextField();
        jButtonFechar = new javax.swing.JButton();
        jButtonExcluirObra = new javax.swing.JButton();
        jButtonAlterarObra = new javax.swing.JButton();
        jLabelAno = new javax.swing.JLabel();
        jTextFieldAno = new javax.swing.JTextField();
        jButtonReservarObra = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jButtonExcluirExemplares.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/cancelar_menor.png"))); // NOI18N
        jButtonExcluirExemplares.setText("Exluir");
        jButtonExcluirExemplares.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExcluirExemplaresActionPerformed(evt);
            }
        });

        jButtonAdicionarExemplares.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/adicionar_menor.png"))); // NOI18N
        jButtonAdicionarExemplares.setText("Adicionar");
        jButtonAdicionarExemplares.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAdicionarExemplaresActionPerformed(evt);
            }
        });

        jLabelTitulo.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelTitulo.setText("Titulo da Obra");

        jTableExemplares.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código", "Emprestado"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.Boolean.class
            };
            boolean[] canEdit = new boolean [] {
                false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane3.setViewportView(jTableExemplares);

        jTextFieldTitulo.setEnabled(false);

        jTextFieldQuantidadeDisponivel.setEnabled(false);

        jLabelQuantidadeDisponivel.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelQuantidadeDisponivel.setText("Exemplares Disponíveis:");

        jTextFieldQuantidade.setEnabled(false);

        jLabelAutor.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelAutor.setText("Autor:");

        jTextFieldEdicao.setEnabled(false);

        jTextFieldAutor.setEnabled(false);

        jComboBoxCategoria.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "LIVRO", "PERIÓDICO", "ENCICLOPÉDIA", "MIDIA", "DICIONÁRIO", "MAPA" }));
        jComboBoxCategoria.setEnabled(false);

        jLabelQuantidadeDisponivel1.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelQuantidadeDisponivel1.setText("Reservas");

        jLabelCategoria.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelCategoria.setText("Categoria:");

        jLabelEdicao.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelEdicao.setText("Edição:");

        jTextFieldQuantidadeDisponivel1.setEnabled(false);

        jLabelEditora.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelEditora.setText("Editora:");

        jLabelExemplaresDisponiveis.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelExemplaresDisponiveis.setText("Exemplares");

        jLabelQuanditade.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelQuanditade.setText("Quantidade de Exemplares:");

        jTextFieldEditora.setEnabled(false);

        jButtonFechar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/cancelar.png"))); // NOI18N
        jButtonFechar.setText("Fechar");
        jButtonFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonFecharActionPerformed(evt);
            }
        });

        jButtonExcluirObra.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/lixeira.png"))); // NOI18N
        jButtonExcluirObra.setText("Excluir Obra");
        jButtonExcluirObra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExcluirObraActionPerformed(evt);
            }
        });

        jButtonAlterarObra.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones/editar.png"))); // NOI18N
        jButtonAlterarObra.setText("Alterar Obra");
        jButtonAlterarObra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAlterarObraActionPerformed(evt);
            }
        });

        jLabelAno.setFont(new java.awt.Font("Arial Black", 0, 14)); // NOI18N
        jLabelAno.setText("Ano");

        jTextFieldAno.setEnabled(false);

        jButtonReservarObra.setText("Reservar Obra");
        jButtonReservarObra.setEnabled(false);
        jButtonReservarObra.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonReservarObraActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(49, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabelCategoria)
                        .addGap(42, 42, 42)
                        .addComponent(jComboBoxCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabelTitulo)
                        .addGap(12, 12, 12)
                        .addComponent(jTextFieldTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 635, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabelExemplaresDisponiveis)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(jButtonFechar, javax.swing.GroupLayout.PREFERRED_SIZE, 135, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButtonExcluirObra)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jButtonAlterarObra))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabelAutor)
                                .addGap(74, 74, 74)
                                .addComponent(jTextFieldAutor, javax.swing.GroupLayout.PREFERRED_SIZE, 176, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabelEdicao)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextFieldEdicao)
                                .addGap(18, 18, 18)
                                .addComponent(jLabelAno)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jButtonExcluirExemplares, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                        .addComponent(jButtonAdicionarExemplares)))
                                .addGap(27, 27, 27)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabelQuanditade)
                                    .addComponent(jLabelQuantidadeDisponivel)
                                    .addComponent(jLabelQuantidadeDisponivel1))
                                .addGap(18, 18, 18)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jTextFieldAno, javax.swing.GroupLayout.PREFERRED_SIZE, 61, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabelEditora)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jTextFieldEditora))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(jTextFieldQuantidadeDisponivel1, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jButtonReservarObra))
                                    .addComponent(jTextFieldQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextFieldQuantidadeDisponivel, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(0, 0, Short.MAX_VALUE)))))
                .addGap(24, 24, 24))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(37, 37, 37)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(jLabelCategoria))
                    .addComponent(jComboBoxCategoria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(22, 22, 22)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(2, 2, 2)
                        .addComponent(jLabelTitulo))
                    .addComponent(jTextFieldTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(16, 16, 16)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jTextFieldEditora, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jLabelEditora)
                                .addComponent(jTextFieldAno, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(2, 2, 2)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                    .addComponent(jLabelEdicao)
                                    .addComponent(jTextFieldEdicao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabelAno)
                                    .addComponent(jTextFieldAutor, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jLabelAutor)))
                .addGap(39, 39, 39)
                .addComponent(jLabelExemplaresDisponiveis)
                .addGap(12, 12, 12)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(2, 2, 2)
                                .addComponent(jLabelQuanditade)
                                .addGap(22, 22, 22)
                                .addComponent(jLabelQuantidadeDisponivel))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jTextFieldQuantidade, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jTextFieldQuantidadeDisponivel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jTextFieldQuantidadeDisponivel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabelQuantidadeDisponivel1)
                            .addComponent(jButtonReservarObra))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAdicionarExemplares)
                    .addComponent(jButtonExcluirExemplares))
                .addGap(59, 59, 59)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jButtonExcluirObra)
                        .addComponent(jButtonAlterarObra))
                    .addComponent(jButtonFechar))
                .addContainerGap(13, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonExcluirExemplaresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExcluirExemplaresActionPerformed
        int selectedRow = jTableExemplares.getSelectedRow();
        String menssagem = "Nenhum exemplar selecionado!";
        if (selectedRow != -1) {
            int id = (int) jTableExemplares.getModel().getValueAt(selectedRow, 0);
            Dao<Exemplar> exemplarDao = new Dao<>(Exemplar.class);
            Exemplar exemplar = exemplarDao.get(id);
            if (exemplar != null) {
                if (exemplar.isEmprestado()) {
                    menssagem = "Exemplar emprestado!";
                } else {
                    List<Exemplar> exemplares = obra.getExemplares();
                    exemplares.remove(exemplar);
                    obra.setExemplares(exemplares);
                    exemplarDao.remove(id);
                    atualizarTabela();
                    menssagem = "";
                }
            }
        }
        if (!menssagem.isEmpty()) {
            JOptionPane.showMessageDialog(this, menssagem, "Erro", JOptionPane.ERROR_MESSAGE);
        }
    }//GEN-LAST:event_jButtonExcluirExemplaresActionPerformed

    private void jButtonAdicionarExemplaresActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAdicionarExemplaresActionPerformed
        new JDialogAdicionarExemplar((JFrame) getParent(), true, obra).setVisible(true);
        if (obra.hasReservas()) {
            List<Reserva> reservas = obra.getReservas();
            for (Reserva reserva : reservas) {
                if (reserva.getEstado().equals(Reserva.Estado.ATIVA)
                        && reserva.getDataLimite() != null
                        && reserva.getDataLimite().after(new Date())) {
                    reserva.setEstado(Reserva.Estado.EXPIRADA);
                }
            }
            Reserva reserva = null;
            int i = 0;
            for (; i < reservas.size(); i++) {
                if (reservas.get(i).getEstado().equals(Reserva.Estado.ATIVA) && reservas.get(i).getDataLimite() == null) {
                    reserva = reservas.get(i);
                    break;
                }
            }

            if (reserva != null) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(new Date());
                calendar.add(Calendar.DAY_OF_MONTH, 2);
                reserva.setDataLimite(calendar.getTime());
                new Dao<Reserva>(Reserva.class).update(reserva);
                reservas.set(i, reserva);
            }
            obra.setReservas(reservas);
            new DaoObra().update(obra);
        }
        atualizarTabela();
    }//GEN-LAST:event_jButtonAdicionarExemplaresActionPerformed

    private void jButtonFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonFecharActionPerformed
        dispose();
    }//GEN-LAST:event_jButtonFecharActionPerformed

    private void jButtonExcluirObraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonExcluirObraActionPerformed
        if (obra.hasEmprestimos()) {
            JOptionPane.showMessageDialog(this, "A obra possui exemplares emprestados!", "Erro", JOptionPane.ERROR_MESSAGE);
        } else {
            int option = JOptionPane.showConfirmDialog(this, "Tem certeza que deseja excluir a obra " + obra.getTitulo() + "?",
                    "Confirmar Exclusão", JOptionPane.YES_NO_OPTION);
            if (option == JOptionPane.YES_OPTION) {
                Dao<Exemplar> daoExemplar = new Dao<>(Exemplar.class);
                for (Exemplar exemplar : obra.getExemplares()) {
                    exemplar.setExcluido(true);
                    daoExemplar.update(exemplar);
                }
                obra.setReservas(null);
                obra.setExcluida(true);
                new DaoObra().update(obra);
                JOptionPane.showMessageDialog(this, "Obra excluída com sucesso!", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            }
        }
    }//GEN-LAST:event_jButtonExcluirObraActionPerformed

    private void jButtonAlterarObraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAlterarObraActionPerformed
        dispose();
        new JDialogCadastrarAlterarObra((JFrame) getParent(), true, obra).setVisible(true);
    }//GEN-LAST:event_jButtonAlterarObraActionPerformed

    private void jButtonReservarObraActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonReservarObraActionPerformed
        Usuario usuarioLogado = JFramePrincipal.getUsuarioLogado();
        if (jButtonReservarObra.getText().equals("Cancelar Reserva")) {
            Reserva reservaAtiva = usuarioLogado.getReservaAtiva(obra);
            reservaAtiva.setEstado(Reserva.Estado.CANCELADA);
            new Dao<Reserva>(Reserva.class).update(reservaAtiva);
            List<Reserva> reservas = obra.getReservas();
            int i = 0;
            for (; i < reservas.size(); i++) {
                if (reservas.get(i).getId() == reservaAtiva.getId()) {
                    break;
                }
            }
            reservas.set(i, reservaAtiva);
            obra.setReservas(reservas);
            new DaoObra().update(obra);
            reservas = usuarioLogado.getReservas();
            for (i = 0; i < reservas.size(); i++) {
                if (reservas.get(i).getId() == reservaAtiva.getId()) {
                    break;
                }
            }
            reservas.set(i, reservaAtiva);
            usuarioLogado.setReservas(reservas);
            new DaoUsuario().update(usuarioLogado);
            atualizarTabela();
            jButtonReservarObra.setText("Reservar Obra");
        } else if (usuarioLogado.getPerfil().getMaxEmprestimos() <= (usuarioLogado.getEmprestimosAtivos().size() + usuarioLogado.getReservasAtivas().size())) {
            JOptionPane.showMessageDialog(this, "Você atingiu o máximo de empréstimos, portanto não pode reservar obras!", "Erro", JOptionPane.ERROR_MESSAGE);
        } else {
            Reserva reserva = new Reserva();
            reserva.setUsuario(usuarioLogado);
            reserva.setObra(obra);
            new Dao<Reserva>(Reserva.class).insert(reserva);
            List<Reserva> reservas = obra.getReservas();
            reservas.add(reserva);
            obra.setReservas(reservas);
            new DaoObra().update(obra);
            reservas = usuarioLogado.getReservas();
            reservas.add(reserva);
            usuarioLogado.setReservas(reservas);
            new DaoUsuario().update(usuarioLogado);
            JOptionPane.showMessageDialog(this, "Reserva efetuada com sucesso!", "Sucesso", JOptionPane.INFORMATION_MESSAGE);
            atualizarTabela();
            jButtonReservarObra.setText("Cancelar Reserva");
        }
    }//GEN-LAST:event_jButtonReservarObraActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAdicionarExemplares;
    private javax.swing.JButton jButtonAlterarObra;
    private javax.swing.JButton jButtonExcluirExemplares;
    private javax.swing.JButton jButtonExcluirObra;
    private javax.swing.JButton jButtonFechar;
    private javax.swing.JButton jButtonReservarObra;
    private javax.swing.JComboBox jComboBoxCategoria;
    private javax.swing.JLabel jLabelAno;
    private javax.swing.JLabel jLabelAutor;
    private javax.swing.JLabel jLabelCategoria;
    private javax.swing.JLabel jLabelEdicao;
    private javax.swing.JLabel jLabelEditora;
    private javax.swing.JLabel jLabelExemplaresDisponiveis;
    private javax.swing.JLabel jLabelQuanditade;
    private javax.swing.JLabel jLabelQuantidadeDisponivel;
    private javax.swing.JLabel jLabelQuantidadeDisponivel1;
    private javax.swing.JLabel jLabelTitulo;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTableExemplares;
    private javax.swing.JTextField jTextFieldAno;
    private javax.swing.JTextField jTextFieldAutor;
    private javax.swing.JTextField jTextFieldEdicao;
    private javax.swing.JTextField jTextFieldEditora;
    private javax.swing.JTextField jTextFieldQuantidade;
    private javax.swing.JTextField jTextFieldQuantidadeDisponivel;
    private javax.swing.JTextField jTextFieldQuantidadeDisponivel1;
    private javax.swing.JTextField jTextFieldTitulo;
    // End of variables declaration//GEN-END:variables

    private void preencherCampos() {
        jComboBoxCategoria.setSelectedItem(obra.getCategoria());
        jTextFieldAutor.setText(obra.getAutor());
        jTextFieldTitulo.setText(obra.getTitulo());
        jTextFieldEdicao.setText(String.valueOf(obra.getEdicao()));
        jTextFieldEditora.setText(obra.getEditora());
        jTextFieldAno.setText(String.valueOf(obra.getAno()));
        atualizarTabela();
    }

    private void atualizarTabela() {
        DefaultTableModel model = (DefaultTableModel) jTableExemplares.getModel();
        model.setRowCount(0);
        Object[] rowData = new Object[2];
        int qtdEmprestados = 0;
        List<Exemplar> exemplares = obra.getExemplares();
        for (Exemplar exemplar : exemplares) {
            if (!exemplar.isExcluido()) {
                rowData[0] = exemplar.getId();
                rowData[1] = exemplar.isEmprestado();
                qtdEmprestados = exemplar.isEmprestado() ? qtdEmprestados + 1 : qtdEmprestados + 0;
                model.addRow(rowData);
            }
        }
        jTableExemplares.setModel(model);
        jTextFieldQuantidade.setText(String.valueOf(exemplares.size()));
        jTextFieldQuantidadeDisponivel.setText(String.valueOf(exemplares.size() - qtdEmprestados));
        int qtdReservas = obra.getReservasAtivas().size();
        if (qtdReservas > 0) {
            jButtonReservarObra.setEnabled(true);
        }
        jTextFieldQuantidadeDisponivel1.setText(String.valueOf(qtdReservas));
    }

    public void setObra(Obra obra) {
        this.obra = obra;
    }

}
